#define _CRT_SECURE_NO_WARNINGS 1
#include "heap.h"
void HpInit(Heap* php)
{
	assert(php);
	php->a = NULL;
	php->size = php->capacity = 0;
}
void HpDestroy(Heap* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->size = php->capacity = 0;
}
void Swap(HpDataType* a, HpDataType* b)
{
	HpDataType tmp = *a;
	*a = *b;
	*b = tmp;
}

void AdjustUp(Heap* php)
{
	assert(php);

	int child = php->size - 1;
	int parent = (child - 1) / 2;

	while (child > 0)
	{
		if (php->a[child] < php->a[parent])
		{

			Swap(&php->a[child], &php->a[parent]);
			child = parent;
			parent = (child - 1) / 2;


		}
		else
		{
			break;
		}

	}
	


}

void HpPush(Heap* php, HpDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HpDataType* tmp = (HpDataType*)realloc(php->a, sizeof(HpDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;
	AdjustUp(php);
}
void AdjustDown(Heap* php,int n)
{
	int parent = 0;
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && php->a[child] > php->a[child + 1])
		{
			child++;
		}
		if (php->a[child] < php->a[parent])
		{
			Swap(&php->a[child], &php->a[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
		

	}
}

void HpPop(Heap* php)
{
	assert(php);
	assert(php->size);
	Swap(&php->a[php->size - 1], &php->a[0]);
	php->size--;
	AdjustDown(php,php->size);

}
HpDataType HpTop(Heap* php)
{
	assert(php);
	assert(php->size);
	return php ->a[0];
}


bool HpEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}